﻿using Hotel.Domain;
using Hotel.Repositories.Dics;
using Hotel.Repositories;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
using NuGet.Packaging;
using Microsoft.AspNetCore.Mvc.Controllers;

namespace Hotel.Web.Filters
{
    public class CacheFilterAttribute : Attribute, IAsyncResourceFilter, IOrderedFilter
    {
        public CacheFilterAttribute(string Key = null,params string[] Operate)
        {
            this.Operate.AddRange(Operate);
        }

        public string[] Operate { get; set; } = { "Create", "Edit", "Delete" };

        public int Order => 999;

        public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
        {
            await next();

            var requestService = context.HttpContext.RequestServices;

            var cache = requestService.GetService<IDistributedCache>();

            var Descriptor = context.ActionDescriptor as ControllerActionDescriptor;

            if(Operate.Contains(Descriptor.ActionName) && context.HttpContext.Request.Method.ToUpper() == "POST")
            {
                await cache.RemoveAsync(Descriptor.ControllerName);
            }
        }
    }
}
